/**
 * build_project
 * <p>
 * Copyright 2014 cayden.cn, Inc. All rights reserved.
 *
 * @author Administrator
 * @date 2021-06-23 11:38
 */
package com.cayden.config.boot.listener;

import com.cayden.config.EnvironmentHolder;
import com.cayden.config.boot.Apps;
import com.cayden.config.boot.EnvironmentContextHolder;
import com.google.common.base.Strings;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

/**
 *
 * @author cayden
 * @date 2021-06-23 11:38
 */
public class CaydenEnviromentApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, PriorityOrdered {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        new EnvironmentHolder().setEnvironment(event.getEnvironment());
        setProfileIfEnableActiveProfiles(event.getEnvironment());
        new EnvironmentContextHolder().setEnvironment(event.getEnvironment());
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private void setProfileIfEnableActiveProfiles(ConfigurableEnvironment environment) {
        if (Strings.isNullOrEmpty(System.getProperty(Apps.SPRING_PROFILE_ACTIVE))) {
            String profile = environment.getProperty(Apps.SPRING_PROFILE_ACTIVE);
            if (!Strings.isNullOrEmpty(profile)) {
                System.setProperty(Apps.SPRING_PROFILE_ACTIVE, profile);
            }
        }
    }

}
